# -*- coding: utf-8 -*-

from openerp import fields, models, api
from datetime import date, datetime
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
import re
import openerp.addons.decimal_precision as dp

from openerp.addons.web_x import _xhelper as x
from openerp.tools.float_utils import float_compare, float_round

x.debug=True

product_mt = False
product_freight =False
product_tpls={}
main_category = False

def init_commonly_used_data(self,main_product_names):
    md = self.env['ir.model.data']
    global product_mt,product_freight,main_category,product_tpl_bc,product_tpl_qk
    if not product_mt:
        model, product_mt = md.get_object_reference('sale_other_products','product_mt')
    if not product_freight:
        model, product_freight = md.get_object_reference('sale_other_products','product_freight')
    if not main_category:
        model, main_category = md.get_object_reference('sale_other_products','product_category_all_saleable_main')
        print(main_category)
    for product_name in main_product_names:
        if not product_tpls.has_key(product_name):
            x.log([('name','=',product_name),('categ_id.id','child_of',main_category)])
            ptl = self.env['product.template'].search([('name','=',product_name),('categ_id.id','child_of',main_category)],limit=1)
            x.log(ptl)
            product_tpls[product_name] = ptl and ptl.id or 0
            x.log(product_tpls)

class sale_order_line(models.Model):
    _inherit= 'sale.order.line'

    product_template = fields.Many2one(required=False)

class sale_order_other_line(models.Model):
    _name= 'sale.order.other.line'

    # product_template = fields.Many2one('product.template',string=u"产品类型")

    # product_name=fields.Many2one(comodel_name='product.attribute.value',string=u'产品名称',domain="[('id', 'in', possible_values_name[0][2])]")

    # possible_values_name = fields.Many2many(comodel_name='product.attribute.value',compute='_get_possible_attribute_values_name')

    product_id = fields.Many2one(comodel_name='product.product',
                                       string=u'产品名称')

    product_uom = fields.Many2one(
        comodel_name='product.uom', string=u'单位',
        related='product_id.uom_id')

    product_uom_qty = fields.Float(u'数量', digits=dp.get_precision('Product UoS'),required=True)

    price = fields.Float(u'单价(元)', required=True, related='product_id.lst_price')

    order_id = fields.Many2one('sale.order', string=u'订单', required=True, ondelete='cascade')

    # @api.one
    # @api.depends('product_template',
    #              'product_template.attribute_line_ids')
    # def _get_possible_attribute_values_name(self):
    #     print('_get_possible_attribute_values_name',self)
    #     attr_values = self.env['product.attribute.value']
    #     index = 0
    #     for attr_line in self.product_template.attribute_line_ids:
    #         if self.product_template.name==u'施工机具':
    #             if index==0:
    #                 attr_values |= attr_line.value_ids
    #         elif index == 1:
    #             attr_values |= attr_line.value_ids
    #         index +=1
    #     self.possible_values_name = attr_values.sorted()


    # @api.one
    # def action_confirm(self):
    #     print('line confirm',self)
    #     for line in self:
    #         # 搜索相应规格的产品，没有则创建产品
    #         if not line.product_id:
    #             product_name =  line.product_name

    #             att_values_ids = line.product_name
    #             product_obj = self.env['product.product']
    #             # att_values_ids = [attr_line.value and attr_line.value.id
    #             #                   or False
    #             #                   for attr_line in line.product_attributes]
    #             domain = [('product_tmpl_id', '=', line.product_template.id)]
    #             for value in att_values_ids:
    #                 if not value:
    #                     raise exceptions.Warning(
    #                         _("You can not confirm before configuring all"
    #                           " attribute values."))
    #                 domain.append(('attribute_value_ids', '=', value.id))
    #             product = product_obj.search(domain)


class sale_order(models.Model):
    _inherit = 'sale.order'

    order_other_line = fields.One2many('sale.order.other.line', 'order_id', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, string=u'其它产品', copy=True)

    order_product_type = fields.Char(string="订单产品类型")

    @api.model
    def default_get(self, fields):
        res = super(sale_order, self).default_get(fields)
        default_order_product_type = self.env.context.get('default_order_product_type', res.get('order_product_type',False))
        if default_order_product_type:
            res.update({
                'order_product_type':default_order_product_type
            })
        return res

    @api.multi
    def button_update_special(self):
        """ 更新特殊产品数量（木托，运费）"""
        init_commonly_used_data(self,[u'板材',u'砌块'])
        x.log('更新木托和运费数量 %s' % self)
        for order in self:
            (dist_mt_qty,mt_line_ids) = (0,[])
            x.log(order.order_line)

            mt_line = order.order_line.filtered(lambda record: record.product_id.id == product_mt)
            freight_line = order.order_line.filtered(lambda record: record.product_id.id == product_freight)

            filter_ptl_id =  lambda record,tpl_id: (record.product_id and record.product_id.product_tmpl_id.id == tpl_id) or (record.product_template and record.product_template.id==tpl_id)
            bc_tpl = product_tpls[u'板材']
            qk_tpl = product_tpls[u'砌块']
            print(bc_tpl,qk_tpl)
            bc_line = order.order_line.filtered(lambda record: filter_ptl_id(record,bc_tpl))
            qk_line = order.order_line.filtered(lambda record: filter_ptl_id(record,qk_tpl))
            # qk_line = order.order_line.filtered(lambda record: (record.product_id and record.product_id.product_tmpl_id.id == product_tpls[u'砌块']) or (record.product_template and result.product_template.id==product_tpls[u'砌块']))

            x.log('bc: ',bc_line)
            x.log('qk:',qk_line)
            dist_mt_qty =sum([line.product_uos_qty for line in qk_line])

            x.log('mt:%s,%s,%s' % (product_mt,dist_mt_qty,mt_line))
            # 添加木托
            if dist_mt_qty >0 and not mt_line:
                x.log('create mt_line')
                mt_line = self.env['sale.order.line'].create({
                    'product_id': product_mt,
                    'product_uom_qty': dist_mt_qty,
                    'order_id': order.id,
                    'price_unit': 2,
                })
            # 添加运费
            if not freight_line:
                # todo:运费计算
                freight_line = self.env['sale.order.line'].create({
                    'product_id': product_freight,
                    'product_uom_qty': 3,
                    'order_id': order.id,
                    'price_unit': 60,
                })

            if mt_line:
                mt_line.product_uom_qty = dist_mt_qty
            if freight_line:
                freight_line.product_uom_qty = 3
                freight_line.price= 60
            order.update_order_other_line([u'砌块',u'板材'])

    @api.one
    def update_order_line(self):
        for order_other_line in self.order_other_line:
            order_line_i = self.order_line.filtered(lambda record: record.product_id in order_other_line.product_id)
            if not order_line_i:
                vals = {
                    'product_id': order_other_line.product_id.id,
                    'product_uom_qty': order_other_line.product_uom_qty,
                    'order_id': self.id,
                    'price_unit': order_other_line.price
                }
                order_line_i = self.env['sale.order.line'].create(vals)
            order_line_i.product_uom_qty = order_other_line.product_uom_qty

    @api.one
    def action_button_confirm(self):
        res = super(sale_order, self).action_button_confirm()
        print(res)
        self.update_order_line()
        self.button_update_special()

    @api.one
    def update_order_other_line(self,exclude_product_name=[]):
        x.log('update_order_other_line')
        order_line = self.order_line.filtered(lambda record: record.product_id.name not in exclude_product_name)
        for order_line_i in order_line:
            order_other_line = self.order_other_line.filtered(lambda record: record.product_id in order_line_i.product_id)
            if not order_other_line:
                vals = {
                    'product_id': order_line_i.product_id.id,
                    'product_uom_qty': order_line_i.product_uom_qty,
                    'order_id': self.id,
                    'price': order_line_i.price_unit,
                    'product_uom_qty': order_line_i.product_uom_qty
                }
                x.log(vals)
                order_other_line = self.env['sale.order.other.line'].create(vals)
            print(self.order_other_line)


    # @api.one
    # @api.onchange('order_other_line')
    # def onchange_order_other_line(self):
    #     x.log('onchange_order_other_line')
    #     self.update_order_line()

